package com.cloudxingkong.dianyinke.NewTeacher.Ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Adapter.PostDTAdapter;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.NoScrollGridView;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.PhotoUtils;
import com.cloudxingkong.dianyinke.NewTeacher.config.Constans;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class PostDongTai extends AppCompatActivity {
    private EditText etContent;
    private CheckBox cbAddr;
    private Spinner spinner;
    private ArrayAdapter<String> stringArrayAdapter;
    private SharedPreferences sharedPreferences;
    private String sessionID,content,spSelectItem,picPath;

    private static final int SELECT_PIC_BY_TAKE_PHOTO=1;
    private static final int SELECT_PIC_BY_PICK_PHOTO=2;
    private Uri photoUri;

    private List<Bitmap> imgList=new ArrayList<>();
    private NoScrollGridView gridView;
    private PostDTAdapter dtAdapter;
    private ProgressDialog progressDialog;

    private boolean isSuccess=false;
    private boolean isCheckedAddr=false;

    private ArrayList<String> pathList=new ArrayList<>();
    private static final int REQUEST_IMAGE=2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_dong_tai);
        init();
        gridView.setAdapter(dtAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (imgList.size() < 4) {
                    if (position > imgList.size() - 1) {
                        selectImg();
                    } else {
                        Toast.makeText(PostDongTai.this, "放大什么的", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(PostDongTai.this, "最多选4张哦~", Toast.LENGTH_SHORT).show();
                    return;
                }
                dtAdapter.notifyDataSetChanged();
            }
        });

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(PostDongTai.this)
                        .setMessage("是否删除图片")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (pathList.size() > 0&&imgList.size()>0) {
                                    try {
                                        pathList.remove(position);
                                        imgList.remove(position);
                                        dtAdapter.notifyDataSetChanged();
                                    }catch (Exception e) {
                                        Log.e("test", "图片移除 " + e.getMessage());
                                    }
                                }else {
                                    Log.e("test", "图片集合为0");
                                }
                            }
                        })
                        .setNegativeButton("取消", null).create().show();
                return true;
            }
        });

        /** Spinner*/
        stringArrayAdapter = new ArrayAdapter<String>(this,
                android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item,
                Constans.WHO_CAN_SEE);
        spinner.setAdapter(stringArrayAdapter);


    }

    private void selectImg() {
        int maxNum=4;
        Intent intent=new Intent(PostDongTai.this,MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA,true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,maxNum);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if (pathList != null && pathList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,pathList);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    private void init() {
        gridView = (NoScrollGridView) findViewById(R.id.post_pics_gridview);
        etContent = (EditText) findViewById(R.id.post_et_content);
        cbAddr = (CheckBox) findViewById(R.id.post_cb_addr);
        spinner = (Spinner) findViewById(R.id.post_spinner);
        sharedPreferences = getSharedPreferences("data_dyk", 0);
        sessionID = CookieHelper.getSessionID(sharedPreferences);
        dtAdapter = new PostDTAdapter(this,imgList);
    }

    //发布动态
    public void post(View view) {
        if (TextUtils.isEmpty(etContent.getText())){
            Toast.makeText(PostDongTai.this, "内容为空", Toast.LENGTH_SHORT).show();
            return;
        }else{
            content = etContent.getText().toString();
        }
        progressDialog = ProgressDialog.show(this, null, "正在发表.....", true, false);
        spSelectItem = spinner.getSelectedItem().toString();
        RequestParams params = new RequestParams(ThisUri.SERVER_YUMING + ThisUri.NAMICS_RELEDY);
        params.addHeader("cookie", sessionID);
        params.setMultipart(true);
        params.addBodyParameter("text", content);
        isCheckedAddr = cbAddr.isChecked();
        if (isCheckedAddr){
            //TODO 发布动态位置写死
            params.addBodyParameter("posstr","北京市丰台区花乡汉庭酒店");
            if (!sharedPreferences.getString("Laddress", "").equals("")) {
                String laddresss = sharedPreferences.getString("Laddress", "");
            }
        }

        if (pathList.size() != 0 && pathList != null) {

            Log.e("test", "图片路径集合的大小 " + pathList.size());
            if (pathList.size() > 0) {
                params.addBodyParameter("pic1", new File(pathList.get(0)));
                if (pathList.size()>1){
                    params.addBodyParameter("pic2", new File(pathList.get(1)));
                    if (pathList.size()>2){
                        params.addBodyParameter("pic3", new File(pathList.get(2)));
                        if (pathList.size() > 3) {
                            params.addBodyParameter("pic4", new File(pathList.get(3)));
                        }
                    }
                }
            }
        }

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("test", "发表动态结果 " + result);
                Message msg = handler.obtainMessage();
                msg.what = 1;
                msg.obj = result;
                handler.sendMessage(msg);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String result= (String) msg.obj;
                    HashMap<String, Object> jsonFromLogin = LoginJsonUtils.getJsonFromLogin(result);
                    Object success = jsonFromLogin.get("success");
                    isSuccess= (boolean) success;
                    if (isSuccess==true){
                        Toast.makeText(PostDongTai.this, "发布成功", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        setResult(316);
                        finish();
                    }else{
                        Toast.makeText(PostDongTai.this, "发布失败，请稍后再试", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;

            }
        }
    };

    public void back(View view) {
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                pathList = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (String imgPath : pathList) {
                    PhotoUtils photoUtils=new PhotoUtils();
                    PhotoUtils.CompressOptions options=new PhotoUtils.CompressOptions();
                    options.uri=Uri.fromFile(new File(imgPath));
                    Bitmap bitmap = photoUtils.compressFromUri(this, options);
                    imgList.add(bitmap);
                }
                dtAdapter.notifyDataSetChanged();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void pickPhoto(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }
    private void takePhoto(){
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent=new Intent();
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues contentValues = new ContentValues();
            photoUri=PostDongTai.this.getContentResolver()
                    .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent,SELECT_PIC_BY_TAKE_PHOTO);
        }else{
            Toast.makeText(this,"内存卡不存在",Toast.LENGTH_SHORT).show();
        }
    }

    private void doPhoto(int requestCode,Intent data)
    {
        if(requestCode == SELECT_PIC_BY_PICK_PHOTO )  //从相册取图片，有些手机有异常情况，请注意
        {
            if(data == null)
            {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
            photoUri = data.getData();
            if(photoUri == null )
            {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor =  getContentResolver().query(photoUri,pojo,null,null,null);
        if(cursor != null )
        {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.i("test", "imagePath = " + picPath);
        //每次获取图片时，将图片放入集合中
        pathList.add(picPath);
        //对图片进行压缩处理
        PhotoUtils photoUtils=new PhotoUtils();
        PhotoUtils.CompressOptions options=new PhotoUtils.CompressOptions();
        options.uri=Uri.fromFile(new File(picPath));
        Bitmap bitmap = photoUtils.compressFromUri(this, options);

        imgList.add(bitmap);

        dtAdapter.notifyDataSetChanged();

    }

}